﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Xml;

namespace Clarius.Silverlight.Streaming.Library.Operations
{
    internal class RetrieveFileSetsOperation : SilverlightStreamingOperation
    {

        internal RetrieveFileSetsOperation(AccountManager accountManager)
        {
            base.Initialize(accountManager);
        }

        protected override void HandleErrorFromHttpStatusCode(HttpStatusCode statusCode, String errorText, Exception ex)
        {
            // let's peek at the status code of the response to try to wrap the error
            // into something more meaningful
            switch (statusCode)
            {
                // a BadRequest in this case means the account data is not valid
                case HttpStatusCode.BadRequest:
                    // TODO: move to SR
                    throw new SilverlightStreamingException("Invalid account data", ex);

                // any other unknown code is unknown for now
                default:
                    WebUtil.ThrowUnknownError(ex);
                    break;
            }
        }

        protected override WebRequest GetWebRequest()
        {
            WebRequest request;

            if (accountManager.MaxItems != Int32.MaxValue)
            {
                // limit the number of returned FileSets to maxItems
                request = WebUtil.GetWebRequest(accountManager.Account, "?max-items=" + accountManager.MaxItems.ToString());
            }
            else
            {
                request = WebUtil.GetWebRequest(accountManager.Account);
            }

            request.Method = WebUtil.HTTP_METHOD_GET;
            return request;
        }

        protected override object ParseWebResponse(string responseText)
        {
            List<FileSet> listOfFileSet = new List<FileSet>();
            XmlDocument xmlContent = new XmlDocument();
            xmlContent.LoadXml(responseText);
            XmlNodeList fileNodes = xmlContent.GetElementsByTagName("fileSet");
            foreach (XmlNode node in fileNodes)
            {
                string filename = node.Attributes["name"].Value;
                bool isApp;
                Boolean.TryParse(node.Attributes["isApp"].Value, out isApp);
                FileSet fs = new FileSet(filename, isApp, accountManager);
                listOfFileSet.Add(fs);
            }

            return listOfFileSet;
        }
    }
}
